bash#!/bin/bash

#作者：刘智伟
#脚本运行命令：【./install.sh 2>&1 | tee install-output.log】
#运行命令说明：安装命令输出终端显示并且在【install-output.log】文件中记录，方便排查执行异常信息
#脚本文件其他事项：Windows环境编辑完改脚本，再Linux执行时可能会因为换行符的特殊报错，需执行【sed -i 's/\r$//' install.sh】处理


#默认安装根目录(根目录可以根据需要修改，例如：/home/soft)
INSTALL_ROOT_HOME=/home/soft
#默认安装包资源目录(安装资源包目录建议使用【/home/soft-install】约定好的即可，无需修改)
RESOURCES_PACKAGE_PATH=/home/soft-install



#=============================各程序安装包配置(配置时确保与安装资源路径【/home/soft-install】下的压缩文件名称一致) - 开始==========================================
#[jdk]安装包
_JDK_ZIP_FILE=jdk-8u221-linux-x64.tar.gz

#[mysql]安装包
_MYSQL_ZIP_FILE=mysql-5.7.38-linux-glibc2.12-x86_64.tar.gz

#[redis]安装包
_REDIS_ZIP_FILE=redis-7.4.1.tar.gz

#[nginx]安装包
_NGINX_ZIP_FILE=nginx-1.22.0.tar.gz

#[minio]安装包
_MINIO_RPM_FILE=minio-20241218131544.0.0-1.x86_64.rpm

#[postgreSql]安装包
_POSTGRESQL_ZIP_FILE=postgresql-16.0.tar.gz

#[yasm]安装包
_YASM_ZIP_FILE=yasm-1.3.0.tar.gz

#[ffmpeg]安装包
_FFMPEG_ZIP_FILE=ffmpeg-7.0.2.tar.xz
#=============================各程序安装包配置(配置时确保与安装资源路径【/home/soft-install】下的压缩文件名称一致) - 结束==========================================



#=============================高亮输出显示设置 - 开始==========================================
#fonts color
yellow(){
    echo -e "\033[33m\033[01m$1\033[0m"
}
green(){
    echo -e "\033[34m\033[01m$1\033[0m"
}
blue(){
    echo -e "\033[32m\033[01m$1\033[0m"
}
red(){
    echo -e "\033[31m\033[01m$1\033[0m"
}
#=============================高亮输出显示设置 - 结束==========================================



##1.1 安装【Jdk1.8.0_221】
function install_jdk(){
    #检查安装包是否存在
    is_exists_file $RESOURCES_PACKAGE_PATH/$_JDK_ZIP_FILE

    ##检测是否已经安装java
    is_install java

    echo "解压缩【$_JDK_ZIP_FILE】"
    mkdir -p $INSTALL_ROOT_HOME/java
    tar -zxvf $RESOURCES_PACKAGE_PATH/$_JDK_ZIP_FILE -C $INSTALL_ROOT_HOME/java
    sleep 1

    #jdk解压后目录名称
    FILE_NAME=$(file_name_unzip "$INSTALL_ROOT_HOME/java" "jdk*")

    echo "export JAVA_HOME=$INSTALL_ROOT_HOME/java/$FILE_NAME" >> /etc/profile
    echo "export JRE_HOME=$INSTALL_ROOT_HOME/java/$FILE_NAME/jre" >> /etc/profile
    echo "export CLASSPATH=.:"'$JAVA_HOME'"/lib/dt.jar:"'$JAVA_HOME'"/lib/tools.jar:"'$JRE_HOME'"/lib" >> /etc/profile
    echo "export PATH="'$JAVA_HOME'"/bin:"'$PATH' >> /etc/profile

    echo "加载【profile】"
    source /etc/profile
    source ~/.bashrc
}

##1.2 安装【MySql】
function install_mysql(){
    #检查安装包是否存在
    is_exists_file $RESOURCES_PACKAGE_PATH/$_MYSQL_ZIP_FILE

    ##检测是否已经安装mysql
    is_install mysql

    echo "检查【mariadb】是否已经安装，已安装就先卸载【mariadb】"
    MARIADB_PKGS=$(rpm -qa | grep mariadb)
    if [ $? -eq 0 ]; then
        echo "当前系统已经安装了【mariadb】，即将卸载"
        for PKG in $MARIADB_PKGS; do
            rpm -e $PKG --nodeps
        done
        echo "【mariadb】，卸载完成！"
    fi

    # 根据数据库安装包文件名获取数据库版本号
    MYSQL_VERSION=$(echo "$_MYSQL_ZIP_FILE" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n 1)
    # 创建【mysql】数据库安装目(不含存储目录部分)
    echo ""
    mkdir -p $INSTALL_ROOT_HOME/mysql

    echo "创建【mysql】数据库数据存储目录【$INSTALL_ROOT_HOME/mysql/data】"
    MYSQL_DATA=$INSTALL_ROOT_HOME/mysql/data
    mkdir -p $MYSQL_DATA

    # 创建用户组及用户【mysql:mysql】
    # -r 参数表示mysql用户是系统用户，不可用于登录系统。
    # -g 参数表示把mysql用户添加到mysql用户组中。
    echo "创建用户组及用户【mysql:mysql】"
    groupadd mysql
    useradd -r -g mysql mysql

    echo "解压缩【$_MYSQL_ZIP_FILE】"
    tar -zxvf $RESOURCES_PACKAGE_PATH/$_MYSQL_ZIP_FILE
    sleep 1

    #mysql解压后文件目录
    UNZIP_FILE_NAME=$(file_name_unzip "$RESOURCES_PACKAGE_PATH" "mysql-")

    echo "进入安装目录【$INSTALL_ROOT_HOME/mysql】"
    cd $INSTALL_ROOT_HOME/mysql
    mv $RESOURCES_PACKAGE_PATH/$UNZIP_FILE_NAME/ mysql-$MYSQL_VERSION

    echo "递归授权【mysql】安装目录给【mysql】用户"
    chown -R mysql:mysql $INSTALL_ROOT_HOME/mysql

    # mysql安装目录
    MYSQL_HOME=$INSTALL_ROOT_HOME/mysql/mysql-$MYSQL_VERSION
    echo "初始化【mysql】数据库"
    cd $MYSQL_HOME/bin
    ./mysqld --initialize --user=mysql --basedir=$MYSQL_HOME --datadir=$MYSQL_DATA > $INSTALL_ROOT_HOME/mysql/init_output.txt 2>&1

    # 建立一个链接文件。因为系统默认会查找/usr/bin下的命令。
    ln -s $MYSQL_HOME/bin/mysql /usr/bin

    #===========================【mysql】自启动脚本 - 开始================================
    echo "创建启动脚本，第一次替换时会备份"
    cp $MYSQL_HOME/support-files/mysql.server /etc/init.d/mysql
    sed -i.bak "s@^basedir=@basedir=${MYSQL_HOME}@g;q;" /etc/init.d/mysql
    sed -i "s@^datadir=@datadir=${MYSQL_DATA}@g" /etc/init.d/mysql
    sed -i "s@^datadir_set=@datadir_set=1@g" /etc/init.d/mysql
    
    echo "添加到开机启动"
    sudo chmod a+x /etc/init.d/mysql
    # 在目录/etc/init.d/底下的启动脚本添加到chkconfig策略时可以不写目录前缀
    sudo chkconfig --add mysql
    sleep 1

    echo "启动【mysql】服务"
    service mysql start
    sleep 3

    # 查看mysql启动状态
    service mysql status
    if [ $? -eq 0 ]; then
        echo
        blue "【mysql】启动成功，数据存储路径为："$MYSQL_DATA
    fi
    #===========================【mysql】自启动脚本 - 结束================================


    #===========================【mysql】初始密码修改 - 开始================================
    # 使用grep和awk提取初始化密码
    echo "使用grep和awk提取初始化密码"
    TEMPORARY_PASSWORD=$(grep 'temporary password' ${INSTALL_ROOT_HOME}/mysql/init_output.txt | awk '{print $NF}' | sed 's/[: ]//g')
    # 输出提取的初始化密码
    if [ -n "$TEMPORARY_PASSWORD" ]; then
        echo "MySQL临时初始化密码是: "$TEMPORARY_PASSWORD

        # 修改初始密码为新的数据库密码
        read -p "请输入mysql密码:" NEW_PWD
        mysqladmin -uroot -p"$TEMPORARY_PASSWORD" password "$NEW_PWD"
        if [ $? -eq 0 ]; then
            echo "mysql密码修改完成"
        else
            yellow "mysql密码修改失败，请手动执行：mysqladmin -uroot -p$TEMPORARY_PASSWORD password $NEW_PWD"
        fi
    else
        echo "无法从【${INSTALL_ROOT_HOME}/mysql/init_output.txt】文件中找到初始化密码。"
    fi
    #===========================【mysql】初始密码修改 - 结束================================


    #===========================【mysql】创建远程访问者账号 - 开始================================
    # 该账号的权限可根据实际情况授权
    echo "创建远程访问者账号【user：super，pass：super@1234】"
    mysql -uroot -p$NEW_PWD -e "use mysql;CREATE USER 'super'@'%' IDENTIFIED BY 'super@1234';GRANT ALL PRIVILEGES ON mysql.* TO 'super';FLUSH PRIVILEGES;"
    #===========================【mysql】创建远程访问者账号 - 结束================================

    echo "重新启动【mysql】服务"
    service mysql restart
    sleep 3

    # 查看mysql启动状态
    service mysql status
    if [ $? -eq 0 ]; then
        echo
        blue "【mysql】启动成功，数据存储路径为："$MYSQL_DATA
    fi
}

##1.3 安装【Redis】
function install_redis(){
    #检查安装包是否存在
    is_exists_file $RESOURCES_PACKAGE_PATH/$_REDIS_ZIP_FILE

    ##检测是否已经安装redis
    is_install redis

    echo "检查程序安装编译环境，没有环境则安装"
    install_compile_environment

    echo "解压缩【$_REDIS_ZIP_FILE】"
    tar -zxvf $RESOURCES_PACKAGE_PATH/$_REDIS_ZIP_FILE
    sleep 1

    #解压后目录名称
    FILE_NAME=$(file_name_unzip "$RESOURCES_PACKAGE_PATH" "redis-")
    echo "即将为您安装【$FILE_NAME】"
    echo "进入安装包减压文件目录"
    cd $RESOURCES_PACKAGE_PATH/$FILE_NAME

    echo "开始编译 make && make install"
    make && make install

    echo "复制[redis.conf]到[/etc/]目录"
    cp $RESOURCES_PACKAGE_PATH/$FILE_NAME/redis.conf /etc/
    echo "redis.conf目录是 /etc/redis.conf"

    #更改pid文件路径
    sed -i "s/pidfile/#pidfile/g" /etc/redis.conf
    echo "pidfile /etc/redis.pid" >> /etc/redis.conf

    #===========================服务注册文件 - 开始================================
    echo "开始写入service服务文件"
    _service_file_path=/usr/lib/systemd/system/redis.service
    touch $_service_file_path
    echo "[Unit]" > $_service_file_path
    echo "Description=Redis" >> $_service_file_path
    echo "After=syslog.target network.target remote-fs.target nss-lookup.target" >> $_service_file_path
    echo "" >> $_service_file_path
    echo "[Service]" >> $_service_file_path
    echo "PIDFile=/etc/redis.pid" >> $_service_file_path
    echo "ExecStart=/usr/local/bin/redis-server /etc/redis.conf" >> $_service_file_path
    echo "ExecReload=/bin/kill -s HUP $MAINPID" >> $_service_file_path
    echo "ExecStop=/bin/kill -s QUIT $MAINPID" >> $_service_file_path
    echo "PrivateTmp=true" >> $_service_file_path
    echo "" >> $_service_file_path
    echo "[Install]" >> $_service_file_path
    echo "WantedBy=multi-user.target" >> $_service_file_path
    #===========================服务注册文件 - 结束================================

    echo "重载系统服务"
    systemctl daemon-reload

    echo "启动redis"
    systemctl start redis

    echo "redis设置为开机自启"
    systemctl enable redis

    systemctl status redis
    if [ $? -eq 0 ]; then
        blue "${FILE_NAME}安装成功，配置文件路径为：/etc/redis.conf"
    fi

    #修改redis密码
    change_redis_pwd

    #开放redis远程访问
    open_redis
}

#修改redis服务密码
function change_redis_pwd(){
    read -p "请输入redis密码:" redis_pwd

    #requirepass注释
    sed -i "s/requirepass/#requirepass/g" /etc/redis.conf
    #重新写入新密码
    echo "requirepass $redis_pwd" >> /etc/redis.conf
    echo "redis密码修改成功，新密码是"$redis_pwd

    systemctl restart redis
    echo "服务重启成功"
    echo
    systemctl status redis 
}

#开放redis远程访问
function open_redis(){
    echo "开启远程访问"
    sed -i "s/bind 127.0.0.1/#bind 127.0.0.1/g" /etc/redis.conf
    sed -i "s/protected-mode/#protected-mode/g" /etc/redis.conf
    echo "开启远程访问成功"

    systemctl restart redis
    echo "服务重启成功"
    echo
    systemctl status redis 
}

##1.4 安装【Nginx】
function install_nginx(){
    #检查安装包是否存在
    is_exists_file $RESOURCES_PACKAGE_PATH/$_NGINX_ZIP_FILE

    ##检测是否已经安装nginx
    is_install nginx

    echo "检查程序安装编译环境，没有环境则安装"
    install_compile_environment

    echo "解压缩【$_NGINX_ZIP_FILE】"
    tar -zxvf $RESOURCES_PACKAGE_PATH/$_NGINX_ZIP_FILE
    sleep 1

    #解压后目录名称
    FILE_NAME=$(file_name_unzip "$RESOURCES_PACKAGE_PATH" "nginx-")
    echo "即将为您安装【$FILE_NAME】"
    echo "进入安装包减压文件目录"
    cd $RESOURCES_PACKAGE_PATH/$FILE_NAME

    echo "指定安装目录"
    NGINX_HOME=$INSTALL_ROOT_HOME/nginx/$FILE_NAME
    mkdir -p $NGINX_HOME
    sleep 1
    ./configure --prefix=$NGINX_HOME

    echo "开始编译 make && make install"
    make && make install

    echo "添加启动项链接【/usr/bin/nginx】"
    ln -s /home/nginx/nginx-1.22.0/sbin/nginx /usr/bin/nginx

    #===========================服务注册文件 - 开始================================
    echo "开始写入service服务文件"
    _service_file_path=/usr/lib/systemd/system/nginx.service
    touch $_service_file_path
    echo "[Unit]" > $_service_file_path
    echo "Description=Nginx" >> $_service_file_path
    echo "After=syslog.target network.target remote-fs.target nss-lookup.target" >> $_service_file_path
    echo "" >> $_service_file_path
    echo "[Service]" >> $_service_file_path
    echo "PIDFile=$NGINX_HOME/logs/nginx.pid" >> $_service_file_path
    echo "ExecStart=$NGINX_HOME/sbin/nginx -c $NGINX_HOME/conf/nginx.conf" >> $_service_file_path
    echo "ExecReload=$NGINX_HOME/sbin/nginx -s reload" >> $_service_file_path
    echo "ExecStop=$NGINX_HOME/sbin/nginx -s stop" >> $_service_file_path
    echo "PrivateTmp=true" >> $_service_file_path
    echo "" >> $_service_file_path
    echo "[Install]" >> $_service_file_path
    echo "WantedBy=multi-user.target" >> $_service_file_path
    #===========================服务注册文件 - 结束================================

    echo "重载系统服务"
    systemctl daemon-reload

    echo "启动nginx"
    systemctl start nginx

    echo "nginx设置为开机自启"
    systemctl enable nginx

    systemctl status nginx
    if [ $? -eq 0 ]; then
        blue "${FILE_NAME}安装成功，配置文件路径为：${NGINX_HOME}/conf/nginx.conf"
    fi
}

##1.5 安装【Minio-2024】
function install_minio(){
    #检查安装包是否存在
    is_exists_file $RESOURCES_PACKAGE_PATH/$_MINIO_RPM_FILE

    ##检测是否已经安装minio
    is_install minio

    echo "开始安装【$_MINIO_RPM_FILE】"
    rpm -ivh $RESOURCES_PACKAGE_PATH/$_MINIO_RPM_FILE
    
    #read -p "请输入minio用户名:" minio_user
    #read -p "请输入minio密码:" minio_pwd

    #===========================配置文件 - 开始================================
    _minio_home=$INSTALL_ROOT_HOME/minio
    echo "写入配置文件【username: minio, password: minio@1234】"
    mkdir -p $_minio_home/conf/
    echo "#数据存放目录" > $_minio_home/conf/minio.conf
    echo "MINIO_VOLUMES=$_minio_home/data" >> $_minio_home/conf/minio.conf
    echo "#端口号设置" >> $_minio_home/conf/minio.conf
    echo "MINIO_OPTS='--console-address :9001 --address :9000'" >> $_minio_home/conf/minio.conf
    echo "#用户名" >> $_minio_home/conf/minio.conf
    echo "MINIO_ROOT_USER='minio'" >> $_minio_home/conf/minio.conf
    echo "#密码" >> $_minio_home/conf/minio.conf
    echo "MINIO_ROOT_PASSWORD='minio@1234'" >> $_minio_home/conf/minio.conf
    #===========================配置文件 - 结束================================
    
    echo "新建minio存储路径："$_minio_home/data
    mkdir -p $_minio_home/data

    #【minio】服务注册文件
    minio_register_service
    
    echo "重载系统服务【systemctl daemon-reload】"
    systemctl daemon-reload

    echo "启动【minio】服务"
    systemctl start minio

    echo "【minio】设置为开机自启"
    systemctl enable minio

    systemctl status minio
    if [ $? -eq 0 ]; then
        echo
        blue "【minio】安装成功，配置文件路径为："$_minio_home"/conf/minio.conf"
    fi
}

#1.5 【minio】服务注册文件
function minio_register_service(){
    #===========================服务注册文件 - 开始================================
    echo "开始写入service服务文件"

    program_path=`which minio`
    _file_path=/usr/lib/systemd/system/minio.service
    touch $_file_path
    echo "[Unit]" > $_file_path
    echo "Description=MinIO" >> $_file_path
    echo "Documentation=https://docs.min.io" >> $_file_path
    echo "Wants=network-online.target" >> $_file_path
    echo "After=network-online.target" >> $_file_path
    echo "#minio文件具体位置" >> $_file_path
    echo "AssertFileIsExecutable=${program_path}" >> $_file_path
    echo "" >> $_file_path
    echo "[Service]" >> $_file_path
    echo "Type=simple" >> $_file_path
    echo "WorkingDirectory=$INSTALL_ROOT_HOME/minio/local" >> $_file_path
    echo "# User and group 用户 组" >> $_file_path
    echo "User=root" >> $_file_path
    echo "Group=root" >> $_file_path
    echo "#创建的配置文件 minio.conf" >> $_file_path
    echo "EnvironmentFile=$INSTALL_ROOT_HOME/minio/conf/minio.conf" >> $_file_path
    echo "ExecStart=${program_path} server "'$MINIO_OPTS'" "'$MINIO_VOLUMES'"" >> $_file_path
    echo "# Let systemd restart this service always" >> $_file_path
    echo "Restart=always" >> $_file_path
    echo "# Specifies the maximum file descriptor number that can be opened by this process" >> $_file_path
    echo "LimitNOFILE=1048576" >> $_file_path
    echo "# Disable timeout logic and wait until process is stopped" >> $_file_path
    echo "TimeoutStopSec=infinity" >> $_file_path
    echo "SendSIGKILL=no" >> $_file_path
    echo "" >> $_file_path
    echo "[Install]" >> $_file_path
    echo "WantedBy=multi-user.target" >> $_file_path
    #===========================服务注册文件 - 开始================================
}

##1.6 安装【postgreSql-16.0】
function install_postgreSql(){
    #检查安装包是否存在
    is_exists_file $RESOURCES_PACKAGE_PATH/$_POSTGRESQL_ZIP_FILE

    ##检测是否已经安装psql
    is_install psql

    echo "检查程序安装依赖环境【readline-devel-*.rpm】，没有环境则安装"
    rpm -qa | grep readline-devel &> /dev/null
    if [ $? -eq 1 ]; then
        yellow "检测到当前环境未安装【readline-devel-*.rpm】依赖，即将安装！"
        #检查安装包是否存在
        is_exists_file $RESOURCES_PACKAGE_PATH/dependencies/ncurses-devel-5.9-14.20130511.el7_4.x86_64.rpm

        echo "开始安装【ncurses-devel-*.rpm】"
        rpm -ivh $RESOURCES_PACKAGE_PATH/dependencies/ncurses-devel-5.9-14.20130511.el7_4.x86_64.rpm

        #检查安装包是否存在
        is_exists_file $RESOURCES_PACKAGE_PATH/dependencies/readline-devel-8.1-4.el9.x86_64.rpm

        echo "开始安装【readline-devel-*.rpm】"
        rpm -ivh $RESOURCES_PACKAGE_PATH/dependencies/readline-devel-8.1-4.el9.x86_64.rpm

        blue "【readline-devel-*.rpm】安装完成！"
        sleep 1
    fi

    echo "解压缩【$_POSTGRESQL_ZIP_FILE】"
    tar -zxvf $RESOURCES_PACKAGE_PATH/$_POSTGRESQL_ZIP_FILE
    sleep 1

    #解压后目录名称
    FILE_NAME=$(file_name_unzip "$RESOURCES_PACKAGE_PATH" "postgresql-")
    echo "即将为您安装【$FILE_NAME】"
    echo "进入安装包减压文件目录"
    cd $RESOURCES_PACKAGE_PATH/$FILE_NAME

    echo "创建安装目录"
    POSTGRESQL_HOME=$INSTALL_ROOT_HOME/postgresql/$FILE_NAME
    mkdir -p $POSTGRESQL_HOME
    sleep 1

    echo "指定安装目录"
    ./configure --prefix=$POSTGRESQL_HOME --without-icu
    sleep 3

    echo "开始编译 make && make install"
    make && make install

    echo "创建用户【postgres】并设置密码(输入密码时会提示：无效的密码： 密码未通过字典检查 - 过于简单化/系统化、密码包含用户名在某些地方，类似提示不是错误，只是警告，继续输入即可设置成功！)"
    sudo useradd postgres
    sudo passwd postgres

    echo "设置用户权限"
    chmod +rw /etc/sudoers
    echo "postgres    ALL=(ALL)       ALL" >> /etc/sudoers
    echo "还原【/etc/sudoers】策略权限"
    pkexec chmod 0440 /etc/sudoers

    echo "指定数据存储目录（数据库特定用户拥有权限的目录，否则不能初始化数据库）"
    POSTGRESQL_DATA=$INSTALL_ROOT_HOME/postgresql/data
    mkdir -p $POSTGRESQL_DATA
    sudo chown -R postgres:postgres $POSTGRESQL_DATA
    sleep 1

    echo "进入安装目录【$POSTGRESQL_HOME】"
    cd $POSTGRESQL_HOME/bin

    ./pg_config
    if [ $? -eq 0 ]; then
        echo
        blue "【postgresql】安装成功，配置文件路径为："$POSTGRESQL_HOME"/bin/pg_config"
    fi

    echo "切换【postgres】用户初始化数据库"
    su postgres
    ./initdb -D $POSTGRESQL_DATA/

    echo "添加启动项链接【/usr/bin/pg_ctl】"
    rm -rf /usr/bin/pg_ctl
    ln -s $POSTGRESQL_HOME/bin/pg_ctl /usr/bin/pg_ctl

    echo "启动【postgresql】，并指定数据目录和日志文件"
    mkdir -p $INSTALL_ROOT_HOME/postgresql/logs
    sudo chown -R postgres:postgres $INSTALL_ROOT_HOME/postgresql/logs
    pg_ctl -D $POSTGRESQL_DATA/ -l $INSTALL_ROOT_HOME/postgresql/logs/pgsql.log start

    #===================================设置数据库默认用户密码-开始===============================================
    echo "进入【psql】终端设置数据库默认用户【postgres】的密码"
    psql
    alter user postgres with encrypted password 'postgres@1234';
    exit
    #===================================设置数据库默认用户密码-结束===============================================

    echo "设置远程连接【host: all】"
    echo "host    all             all             0.0.0.0/0               md5" >> $POSTGRESQL_DATA/pg_hba.conf
    #sed -i "s/listen_addresses = 'localhost'/#listen_addresses = 'localhost'/g"
    echo "listen_addresses = '*'" >> $POSTGRESQL_DATA/postgresql.conf

    echo "配置环境变量"
    echo "export POSTGRESQL_HOME=$POSTGRESQL_HOME" >> /etc/profile
    echo "export PATH="'$POSTGRESQL_HOME'"/bin:"'$PATH' >> /etc/profile

    echo "加载【profile】"
    source /etc/profile
    source ~/.bashrc

    echo "授权【pgsql】安装目录给用户【postgres】"
    sudo chown -R postgres:postgres $INSTALL_ROOT_HOME/postgresql
    #===========================【postgresql】自启动脚本（方式一，选其一即可） - 开始================================
    echo "创建启动脚本，第一次替换时会备份"
    cp $RESOURCES_PACKAGE_PATH/$FILE_NAME/contrib/start-scripts/linux /etc/init.d/pgsql
    sed -i.bak "s@^prefix=/usr/local/pgsql@prefix=${POSTGRESQL_HOME}@g" /etc/init.d/pgsql
    sed -i 's@^PGDATA="/usr/local/pgsql/data"@PGDATA="'$POSTGRESQL_DATA'"@g' /etc/init.d/pgsql
    sed -i 's@^PGLOG="$PGDATA/serverlog"@PGLOG="'$INSTALL_ROOT_HOME'/postgresql/logs/pgsql.log"@g' /etc/init.d/pgsql
    
    echo "添加到开机启动"
    sudo chmod a+x /etc/init.d/pgsql
    # 在目录/etc/init.d/底下的启动脚本添加到chkconfig策略时可以不写目录前缀
    sudo chkconfig --add pgsql
    sleep 1

    echo "启动【pgsql】服务"
    service pgsql start
    sleep 3

    # 查看pgsql启动状态
    service pgsql status
    if [ $? -eq 0 ]; then
        echo
        blue "【pgsql】启动成功，数据存储路径为：$POSTGRESQL_DATA，日志路径为：$INSTALL_ROOT_HOME/postgresql/logs/pgsql.log"
    fi
    #===========================【postgresql】自启动脚本（方式一，选其一即可） - 开始================================

    #===========================【postgresql】服务注册文件（方式二，选其一即可） - 开始================================
    # echo "开始写入service服务文件"

    # program_path=`which pg_ctl`
    # _file_path=/usr/lib/systemd/system/pgsql.service
    # touch $_file_path
    # echo "[Unit]" > $_file_path
    # echo "Description=PG_Sql" >> $_file_path
    # echo "Wants=network-online.target" >> $_file_path
    # echo "After=network-online.target" >> $_file_path
    # echo "AssertFileIsExecutable=${program_path}" >> $_file_path
    # echo "" >> $_file_path
    # echo "[Service]" >> $_file_path
    # echo "Type=simple" >> $_file_path
    # echo "User=postgres" >> $_file_path
    # echo "Group=postgres" >> $_file_path
    # echo "ExecStart=${program_path} -D $POSTGRESQL_DATA -l $INSTALL_ROOT_HOME/postgresql/logs/pgsql.log start" >> $_file_path
    # echo "ExecReload=${program_path} -D $POSTGRESQL_DATA -l $INSTALL_ROOT_HOME/postgresql/logs/pgsql.log restart" >> $_file_path
    # echo "ExecStop=${program_path} -D $POSTGRESQL_DATA -l $INSTALL_ROOT_HOME/postgresql/logs/pgsql.log stop" >> $_file_path
    # echo "Restart=always" >> $_file_path
    # echo "PrivateTmp=true" >> $_service_file_path
    # echo "" >> $_file_path
    # echo "[Install]" >> $_file_path
    # echo "WantedBy=multi-user.target" >> $_file_path

    # echo "重载系统服务【systemctl daemon-reload】"
    # systemctl daemon-reload

    # echo "【pgsql】设置为开机自启"
    # systemctl enable pgsql

    # echo "启动【pgsql】服务"
    # systemctl start pgsql

    # systemctl status pgsql
    # if [ $? -eq 0 ]; then
    #     echo
    #     blue "【pgsql】启动成功，数据存储路径为：$POSTGRESQL_DATA，日志路径为：$INSTALL_ROOT_HOME/postgresql/logs/pgsql.log"
    # fi
    #===========================【postgresql】服务注册文件（方式二，选其一即可） - 开始================================
}

##1.7 ...

##1.8 安装【yasm-1.3.0】
function install_yasm() {
    #检查安装包是否存在
    is_exists_file $RESOURCES_PACKAGE_PATH/$_YASM_ZIP_FILE

    ##检测是否已经安装yasm
    is_install yasm

    echo "检查程序安装编译环境，没有环境则安装"
    install_compile_environment

    echo "解压缩【$_YASM_ZIP_FILE】"
    tar -zxvf $RESOURCES_PACKAGE_PATH/$_YASM_ZIP_FILE
    sleep 1

    #解压后目录名称
    FILE_NAME=$(file_name_unzip "$RESOURCES_PACKAGE_PATH" "yasm-")
    echo "即将为您安装【$FILE_NAME】"
    echo "进入安装包减压文件目录"
    cd $RESOURCES_PACKAGE_PATH/$FILE_NAME

    echo "指定安装目录"
    YASM_HOME=$INSTALL_ROOT_HOME/ffmpeg/$FILE_NAME
    mkdir -p $YASM_HOME
    ./configure --prefix=$YASM_HOME
    sleep 3

    echo "开始编译 make && make install"
    make && make install

    echo "添加环境变量:【$FILE_NAME】安装目录/bin"
    echo 'export PATH=$PATH:'$YASM_HOME'/bin' >> /etc/profile

    echo "加载【profile】"
    source /etc/profile
    source ~/.bashrc

    echo "yasm安装结果验证："
    yasm --version
}

##1.9 安装【ffmpeg-7.0.2】
function install_ffmpeg() {
    #检查安装包是否存在
    is_exists_file $RESOURCES_PACKAGE_PATH/$_FFMPEG_ZIP_FILE

    ##检测是否已经安装ffmpeg
    is_install ffmpeg

    #检测【yasm】依赖是否安装
    which yasm &> /dev/null
    if [ $? -eq 1 ]; then
        yellow "检测到当前环境未安装【yasm】依赖，即将安装！"
        install_yasm
    fi

    echo "解压缩【$_FFMPEG_ZIP_FILE】"
    tar -xJvf $RESOURCES_PACKAGE_PATH/$_FFMPEG_ZIP_FILE
    sleep 1

    #解压后目录名称
    FILE_NAME=$(file_name_unzip "$RESOURCES_PACKAGE_PATH" "ffmpeg-")
    echo "即将为您安装【$FILE_NAME】"
    echo "进入安装包减压文件目录"
    cd $RESOURCES_PACKAGE_PATH/$FILE_NAME

    echo "指定安装目录"
    FFMPEG_HOME=$INSTALL_ROOT_HOME/ffmpeg/$FILE_NAME
    mkdir -p $FFMPEG_HOME
    ./configure --enable-shared --prefix=$FFMPEG_HOME
    sleep 3

    echo "开始编译 make && make install"
    make && make install

    echo "添加环境变量:【$FILE_NAME】安装目录/bin"
    echo 'export PATH=$PATH:'$FFMPEG_HOME'/bin' >> /etc/profile
    echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:'$FFMPEG_HOME'/lib/' >> /etc/profile

    echo "加载【profile】"
    source /etc/profile
    source ~/.bashrc

    echo "ffmpeg安装结果验证："
    ffmpeg -version
}

#程序安装环境【gcc、g++、make】依赖
function install_compile_environment(){
    mkdir -p $INSTALL_ROOT_HOME/dependencies
    #检查gcc依赖
    echo "开始检查gcc依赖"
    which gcc &> /dev/null
    if [ $? -eq 1 ]; then
        echo "gcc未安装，即将安装，进入gcc目录"
        cd $RESOURCES_PACKAGE_PATH/dependencies/gcc
        sleep 1

        echo "开始安装"
        rpm -Uvh *.rpm --nodeps --force

        echo "gcc安装完成【gcc】"
        gcc -v
    else
        echo "gcc依赖已存在，无需安装"
        gcc -v
    fi

    echo 
    #检查g++依赖
    echo "开始检查g++依赖"
    which g++ &> /dev/null
    if [ $? -eq 1 ]; then
        echo "g++未安装，即将安装，进入g++目录"
        cd $RESOURCES_PACKAGE_PATH/dependencies/g++
        sleep 1

        echo "开始安装【g++】"
        rpm -Uvh *.rpm --nodeps --force

        echo "g++安装完成"
        g++ -v
    else
        echo "g++依赖已存在，无需安装"
        g++ -v
    fi

    echo 
    #检查make依赖
    echo "开始检查make依赖"
    which make &> /dev/null
    if [ $? -eq 1 ]; then
        echo "make未安装，即将安装，进入make目录"
        cd $RESOURCES_PACKAGE_PATH/dependencies/make

        echo "开始安装【make】"
        rpm -Uvh *.rpm --nodeps --force

        echo "make安装完成"
        make -v
    else
        echo "make依赖已存在，无需安装"
        make -v
    fi

    echo 
    #检查openssl依赖
    echo "开始检查openssl依赖"
    which openssl &> /dev/null
    if [ $? -eq 1 ]; then
        echo "openssl未安装，即将安装，进入openssl目录"
        cd $RESOURCES_PACKAGE_PATH/dependencies/openssl-1.0.2h

        echo "开始安装【openssl-1.0.2h】"
        ./config

        echo "开始编译 make && make install"
        make && make install

        echo "openssl安装完成"
        openssl version
    else
        echo "openssl依赖已存在，无需安装"
        openssl version
    fi

    echo 
    #检查pcre依赖
    echo "开始检查pcre依赖"
    which pcregrep &> /dev/null
    if [ $? -eq 1 ]; then
        echo "pcre未安装，即将安装，进入pcre目录"
        cd $RESOURCES_PACKAGE_PATH/dependencies/pcre-8.44

        echo "开始安装【pcre-8.44】"
        ./configure

        echo "开始编译 make && make install"
        make && make install

        echo "pcre安装完成"
        pcregrep -V
    else
        echo "pcre依赖已存在，无需安装"
        pcregrep -V
    fi

    echo 
    #检查zlib依赖
    echo "开始检查zlib依赖"
    which libz.so &> /dev/null
    if [ $? -eq 1 ]; then
        echo "zlib未安装，即将安装，进入zlib目录"
        cd $RESOURCES_PACKAGE_PATH/dependencies/zlib-1.2.11

        echo "开始安装【zlib-1.2.11】"
        ./configure

        echo "开始编译 make && make install"
        make && make install

        echo "zlib安装完成"
        find . -name libz.so
    else
        echo "zlib依赖已存在，无需安装"
        find . -name libz.so
    fi

    echo 
    #检查python3依赖
    echo "开始检查python3依赖"
    which python3 &> /dev/null
    if [ $? -eq 1 ]; then
        echo "python3未安装，即将安装，进入python3目录"
        cd $RESOURCES_PACKAGE_PATH/dependencies/Python-3.6.5

        echo "开始安装【Python-3.6.5】"
        PYTHON3_HOME=$INSTALL_ROOT_HOME/python/Python-3.6.5
        mkdir -p $PYTHON3_HOME
        ./configure --prefix=$PYTHON3_HOME --with-ssl

        echo "开始编译 make && make install"
        make && make install

        echo "添加启动项链接【/usr/bin/python3、/usr/bin/pip3】"
        ln -s $PYTHON3_HOME/bin/python3 /usr/bin/python3
        ln -s $PYTHON3_HOME/bin/pip3 /usr/bin/pip3

        echo "python3安装完成"
        python3 -V
    else
        echo "python3依赖已存在，无需安装"
        python3 -V
    fi
}

#检查程序是否已经安装
function is_install(){
    program_name=$1
    which $program_name &> /dev/null
    if [ $? -eq 0 ]; then
        program_path=`which ${program_path}`
        red "检测到当前已经安装了【"$program_name"】，地址："$program_path
        exit 1
    fi
}

#检查程序【安装包】是否存在
function is_exists_file(){
    #文件全路径
    full_path=$1
    #检查程序【安装包】是否存在
    if [[ -e "$full_path" ]]; then
        blue "当前安装的程序包[$full_path], 即将安装..."
    else
        start_menu
        red "当前安装的程序包不存在[$full_path], 请上传安装包压缩文件到[$RESOURCES_PACKAGE_PATH]目录下"
    fi
}

#压缩文件去后缀获取文件名
function file_name_unzip(){
    DIRS=$(find $1 -type d -name $2"*")
    FILE_NAME=$2
    if [ -n "$DIRS" ]; then
        FILE_NAME=$(echo $DIRS | head -n 1)
        FILE_NAME=$(basename "$FILE_NAME" "$1")
        echo $FILE_NAME
    else
        start_menu
        red "未找到【"$2"】解压后的资源目录："$1"/"$2
    fi
}

#2.1开放防火墙端口
function open_firewalld_port(){
    read -p "请输入要开放的端口号及协议[ 例如: 80/tcp | 3306/tcp | 8080/udp | 3000-4000/tcp ]:" port

    echo "正在开放端口"$port
    firewall-cmd --zone=public --add-port=$port --permanent

    if [ $? -eq 0 ]; then
        echo "开放端口"$port"成功"
    else
        echo "开放端口"$port"失败，请手动执行如下命令
        firewall-cmd --zone=public --add-port=$port --permanent"
    fi

    firewall-cmd --reload
    echo "防火墙重启成功"

    echo
    query_firewalld_port
}

#2.2关闭防火墙端口
function close_firewalld_port(){
    read -p "请输入要关闭的端口号及协议[ 例如: 80/tcp | 3306/tcp | 8080/udp | 3000-4000/tcp ]:" port

    echo "正在关闭端口"$port
    firewall-cmd --zone=public --remove-port=$port --permanent

    if [ $? -eq 0 ]; then
        echo "关闭端口"$port"成功"
    else
        echo "关闭端口"$port"失败，请手动执行如下命令
        firewall-cmd --zone=public --remove-port=$port --permanent"
    fi

    firewall-cmd --reload
    echo "防火墙重启成功"

    echo
    query_firewalld_port
}

#2.3查看防火墙端口
function query_firewalld_port(){
    echo "已经开放的端口如下:"
    firewall-cmd --permanent --list-port
}

start_menu(){
    clear
    cd $RESOURCES_PACKAGE_PATH
    green " =================================================="
    green " 生产环境 一键离线安装脚本 Centos7 x64 By thsrite"
    green " 可安装程序：jdk、minio、yams、ffmpeg、"
    green " 可开放、关闭、查看防火墙端口"
    green " 为防止出现其他问题，请在未安装上述服务的环境中安装 "
    green " =================================================="

    echo
    blue " =====================服务安装====================="
    yellow " 1.1     安装【JDK】"
    yellow " 1.2     安装【MySql】"
    yellow " 1.3     安装【Redis】"
    yellow " 1.4     安装【Nginx】"
    yellow " 1.5     安装【Minio】"
    yellow " 1.6     安装【PostgreSql】"
    yellow " 1.8     安装【yasm：FFmpeg依赖】"
    yellow " 1.9     安装【FFmpeg】"
    # blue " =============================================="

    echo
    blue " =====================端口管理====================="
    yellow " 2.1     开放防火墙端口"
    yellow " 2.2     关闭防火墙端口"
    yellow " 2.3     查看已开放防火墙端口"
    # blue " =============================================="

    echo
    blue " =====================退出脚本====================="
    yellow " 0.  退出脚本"
    blue " =============================================="
    echo
    read -p "请输入菜单编号（格式：数字+点+数字，例如：1.1；0：表示退出），回车【下一步】:" num
    case "$num" in
        #########[1.* 服务安装]#########
        1.1)
            #安装【JDK】"
            install_jdk
            ;;
        1.2)
            #安装【MySql】"
            install_mysql
            ;;
        1.3)
            #安装【Redis】"
            install_redis
            ;;
        1.4)
            #安装【Nginx】"
            install_nginx
            ;;
        1.5)
            #安装【Minio】"
            install_minio
            ;;
        1.6)
            #安装【PostgreSql】"
            install_postgreSql
            ;;
        1.8)
            #安装【yasm】
            install_yasm
            ;;
        1.9)
            #安装【FFmpeg】
            install_ffmpeg
            ;;


        #########[2.* 端口管理]#########
        2.1)
            #开放端口
            open_firewalld_port
            ;;
        2.2)
            #关闭端口
            close_firewalld_port
            ;;
        2.3)
            #查询端口
            query_firewalld_port
            ;;


        #########[3.* 其他待优化功能]#########
        3.1)
            #测试
            test
            ;;


        #########[0 退出]#########
        0)
            exit 1
            ;;


        #########[* 错误指令]#########
        *)
            clear
            red "请输入正确菜单编号（格式：数字+点+数字，例如：1.1；0：表示退出），回车【下一步】:"
            sleep 1s
            start_menu
            ;;
    esac
}

#启动命令
start_menu